package cn.ito.zjgsu.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.ito.zjgsu.utils.impl.CsrfTokenManager;

public class CsrfInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if ("POST".equalsIgnoreCase(request.getMethod())) {

			String csrfToken = CsrfTokenManager.getTokenFromRequest(request);

			if (csrfToken == null || !csrfToken
					.equals(request.getSession().getAttribute(CsrfTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME))) {

				String reLoginUrl = getCurrentUrl(request);
				response.sendRedirect(reLoginUrl);
				return false;

			} else {

				return true;
			}

		} else {
			String csrfToken = CsrfTokenManager.getTokenFromRequest(request);
			if(csrfToken==null){
				csrfToken = CsrfTokenManager.createTokenForSession(request.getSession());
				request.setAttribute(CsrfTokenManager.CSRF_PARAM_NAME, csrfToken);
			}
			return true;

		}

	}

	private String getCurrentUrl(HttpServletRequest request) {
		String currentUrl = request.getHeader("Referer");
		if (!StringUtils.isEmpty(request.getQueryString())) {
			currentUrl += "?" + request.getQueryString();
		}

		return currentUrl;
	}
}